# -*- coding:UTF-8 -*-
from cmdb.models import CategoryInfo

def category_info(search,start,end):
    count = 0
    cRes = {}
    if search == '':
        count=CategoryInfo.objects.count()
        cRes = CategoryInfo.objects.order_by('-grade')[start:end]
    else:
        count=CategoryInfo.objects.filter(category_name__icontains=search).count()
        cRes = CategoryInfo.objects.filter(category_name__icontains=search).order_by('-grade')[start:end]
    return {'count':count,'category_info_list':cRes}

def get_category_infos():
    cAllRes = CategoryInfo.objects.all().values('id','category_name','parent_category','grade')
    return cAllRes

def get_category_info(id):
    cInfo = CategoryInfo.objects.get(id=id)
    return cInfo

def level_category_info(grade):
    cAllRes = CategoryInfo.objects.filter(grade=grade).values('id','category_name','grade')
    return cAllRes

def exclude_level_category_info(grade, id):
    cAllRes = CategoryInfo.objects.exclude(id=id).filter(grade=grade).values('id','category_name','grade')
    return cAllRes

def add_category_info(category_name,grade,parent_category,comment,operator):
    cNewInfo = CategoryInfo(category_name=category_name,grade=grade,parent_category=parent_category,
                            comment=comment,operator=operator)
    cNewInfo.save()

def edit_category_info(id, category_name, grade, parent_category, comment, operator):
    cInfo = CategoryInfo.objects.get(id=id)
    cInfo.category_name = category_name
    cInfo.grade = grade
    cInfo.parent_category = parent_category
    cInfo.comment = comment
    cInfo.operator = operator
    cInfo.save()

def del_category_info(id):
    CategoryInfo.objects.get(id=id).delete()

def exist_children_category_info(id):
    count = CategoryInfo.objects.filter(parent_category=id).count()
    if count > 0:
        return True
    return False